package com.fdb.efp.console.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.fdb.basic.framework.core.util.UUIDUtil;
import com.fdb.efp.console.common.SysReportNameCNEnum;
import com.fdb.efp.console.model.WriteRptAccLoanModel;
import com.fdb.efp.console.service.bo.ExportReportConditionsVO;
import com.fdb.efp.console.service.bo.FileExportListVO;
import com.fdb.efp.console.service.facade.FileExportListService;
import com.fdb.efp.console.service.facade.RptAccLoanService;
import com.fdb.efp.console.service.vo.RptAccLoanVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 需求编号：【2019D0509】（业务提的需求编号）
 * 问题编号：【】（若不是因为修复问题而新增该类，则留空）
 * 开发人员：【wanglh4】
 * 创建日期：【2020/1/14 12:10】
 * 功能描述：
 */
@Service("exportReportDataService")
public class ExportReportDataService {

    @Autowired
    @Qualifier("rptAccLoanService")
    private RptAccLoanService rptAccLoanService;

    @Autowired
    @Qualifier("fileExportListService")
    private FileExportListService fileExportListService;

    @Value("${PAGESIZE}")
    private int pagesize;

    @Value("${TOTALSIZE}")
    private int totalsize;

    private Logger logger = LoggerFactory.getLogger(ExportReportDataService.class);

    public List<RptAccLoanVO> getRepportDatas(ExportReportConditionsVO exportReportConditionsVO) {
        RptAccLoanVO rptAccLoanVO = getRptAccLoanVO(exportReportConditionsVO);
        List<RptAccLoanVO> queryReptAccLoanVORs = rptAccLoanService.queryReportData(rptAccLoanVO);
        return queryReptAccLoanVORs;
    }

    private RptAccLoanVO getRptAccLoanVO(ExportReportConditionsVO exportReportConditionsVO) {
        RptAccLoanVO rptAccLoanVO = new RptAccLoanVO();
        rptAccLoanVO.setBillNo(exportReportConditionsVO.getQurBillNo());
        rptAccLoanVO.setCusName(exportReportConditionsVO.getQurCusName());
        rptAccLoanVO.setPrdId(exportReportConditionsVO.getQurPrd());
        rptAccLoanVO.setPrdType(exportReportConditionsVO.getQurPrdtype());
        rptAccLoanVO.setStaerBusinessDate(exportReportConditionsVO.getQurDateDBeg());
        rptAccLoanVO.setEndBusinessDate(exportReportConditionsVO.getQurDateDEnd());
        return rptAccLoanVO;
    }

    public void copyBeansVal(List<RptAccLoanVO> queryReptAccLoanVORs, List<WriteRptAccLoanModel> modleList) {
        //List<WriteRptAccLoanModel> modleList = new ArrayList<>();
        for (RptAccLoanVO item:queryReptAccLoanVORs) {
            WriteRptAccLoanModel writeRptAccLoanModel = new WriteRptAccLoanModel();
            writeRptAccLoanModel.setContNo(item.getContNo());
            writeRptAccLoanModel.setBillNo(item.getBillNo());
            writeRptAccLoanModel.setApplySeq(item.getApplySeq());
            writeRptAccLoanModel.setApplyDate(item.getApplyDate());
            writeRptAccLoanModel.setCusId(item.getCusId());
            writeRptAccLoanModel.setCusName(item.getCusName());
            writeRptAccLoanModel.setCusNational(item.getCusNational());
            writeRptAccLoanModel.setIndivSex(item.getIndivSex());
            writeRptAccLoanModel.setCertTypeName(item.getCertTypeName());
            writeRptAccLoanModel.setIndivIdExpDt(item.getIndivIdExpDt());
            writeRptAccLoanModel.setCertCode(item.getCertCode());
            writeRptAccLoanModel.setIndivOcc(item.getIndivOcc());
            writeRptAccLoanModel.setPhone(item.getPhone());
            writeRptAccLoanModel.setIndivRsdAddr(item.getIndivRsdAddr());
            writeRptAccLoanModel.setTypeName(item.getTypeName());
            writeRptAccLoanModel.setPrdName(item.getPrdName());
            writeRptAccLoanModel.setLoanAmount(item.getLoanAmount() == null ? BigDecimal.ZERO:item.getLoanAmount());
            writeRptAccLoanModel.setLoanBalance(item.getLoanBalance() == null ? BigDecimal.ZERO:item.getLoanBalance());
            writeRptAccLoanModel.setLoanStartDate(item.getLoanStartDate());
            writeRptAccLoanModel.setLoanEndDate(item.getLoanEndDate());
            writeRptAccLoanModel.setSettlDate(item.getSettlDate());
            writeRptAccLoanModel.setLoanTerm(item.getLoanTerm());
            writeRptAccLoanModel.setTermTypeName(item.getTermTypeName());
            writeRptAccLoanModel.setRepaymentModeName(item.getRepaymentModeName());
            writeRptAccLoanModel.setLoanStateName(item.getLoanStateName());
            writeRptAccLoanModel.setLevelFiveClassName(item.getLevelFiveClassName());
            writeRptAccLoanModel.setRealityIrY(item.getRealityIrY() == null ? BigDecimal.ZERO:item.getRealityIrY());
            writeRptAccLoanModel.setAdjustmentModeName(item.getAdjustmentModeName());
            writeRptAccLoanModel.setGuaranteeModeName(item.getGuaranteeModeName());
            writeRptAccLoanModel.setSurplusPeriod(item.getSurplusPeriod());
            writeRptAccLoanModel.setOverdueDays(item.getOverdueDays() == null ? BigDecimal.ZERO : item.getOverdueDays());
            modleList.add(writeRptAccLoanModel);
        }
        //return modleList;
    }

    public void insertFileExportInfo(ExportReportConditionsVO exportReportConditionsVO, String status, String msg) {
        //将下载信息存入数据库
        FileExportListVO fileExportListVO = new FileExportListVO();
        fileExportListVO.setPkId(UUIDUtil.getUUID());
        fileExportListVO.setFileName(exportReportConditionsVO.getFileName());
        fileExportListVO.setFilePath(exportReportConditionsVO.getFilePath());
        fileExportListVO.setFileDesc("用户" + exportReportConditionsVO.getUserName() + "(" + exportReportConditionsVO.getLoginUserId() + "）在" + exportReportConditionsVO.getExportTime() + "导出的"
                + SysReportNameCNEnum.RPT_ACC_LOAN.getValue() + "(" + SysReportNameCNEnum.RPT_ACC_LOAN.getKey() + ")的详细信息。");
        fileExportListVO.setQueryParam(exportReportConditionsVO.toString());
        fileExportListVO.setStatus(status);
        fileExportListVO.setStatusDesc(msg);
        fileExportListVO.setCreateTime(exportReportConditionsVO.getExportTime());
        fileExportListVO.setCreateUser(exportReportConditionsVO.getLoginUserId());
        fileExportListVO.setCreateUserName(exportReportConditionsVO.getUserName());
        fileExportListVO.setCreateUserOrg(exportReportConditionsVO.getLoginUserOrgCode());
        fileExportListVO.setCreateUserOrgName(exportReportConditionsVO.getOrgName());
        int num = fileExportListService.insertFileExportList(fileExportListVO);
    }

    public void updFileExportListExport(String fileName, String status, String msg){
        FileExportListVO fileExportListVO = new FileExportListVO();
        fileExportListVO.setFileName(fileName);
        fileExportListVO.setStatus(status);
        fileExportListVO.setStatusDesc(msg);
        int num = fileExportListService.updateByFileName(fileExportListVO);
        if(num != 1){
            logger.error("根据参数:" + fileExportListVO.toString() + "更新导出信息出错！");
        }
    }

    public int countDatas(ExportReportConditionsVO exportReportConditionsVO) {
        int num = 0;
        RptAccLoanVO rptAccLoanVO = getRptAccLoanVO(exportReportConditionsVO);
        num = rptAccLoanService.countDatas(rptAccLoanVO);
        return num;
    }

    public void writeDtas(ExportReportConditionsVO exportReportConditionsVO, String filePath, String fileName) throws IOException {
        int count = exportReportConditionsVO.getReportCount();
        logger.info("======>正在处理" +SysReportNameCNEnum.getValue(exportReportConditionsVO.getSysReportName()) + "报表，总数量为:" +count);

        //计算表单个数
        int sheetNum = count / totalsize;
        if ((count % totalsize) != 0) sheetNum += 1;

        RptAccLoanVO rptAccLoanVO = getRptAccLoanVO(exportReportConditionsVO);
        rptAccLoanVO.setSize(pagesize);
        rptAccLoanVO.setTotal(count);

        ExcelWriter writer = EasyExcel.write(filePath, WriteRptAccLoanModel.class).build();
        List<WriteRptAccLoanModel> modleList = new ArrayList<>();

        for(int s = 0; s < sheetNum; s++){
            WriteSheet writeSheet = EasyExcel.writerSheet(s, SysReportNameCNEnum.RPT_ACC_LOAN.getValue() + (s+1)).build();

            //循环次数
            int loopTimes = -1;
            if(count > totalsize){
                loopTimes = totalsize / pagesize;
                if ((totalsize % pagesize) != 0) loopTimes += 1;
            }else{
                loopTimes = count / pagesize;
                if ((count % pagesize) != 0) loopTimes += 1;
            }

            for (int i = 0; i < loopTimes; i++) {
                rptAccLoanVO.setPage(i + 1);
                modleList.clear();
                try{
                    List<RptAccLoanVO> queryReptAccLoanVORs = rptAccLoanService.queryReportDataByPage(rptAccLoanVO);
                    copyBeansVal(queryReptAccLoanVORs, modleList);
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("report middle is error!:{}" ,e.getMessage());
                }

                if (Objects.nonNull(modleList) && !modleList.isEmpty()) {
                    //导出数据
                    writer.write(modleList, writeSheet);
                }
            }

            if(count > totalsize) count = count - totalsize * (s+1);

        }

        writer.finish();
    }



}
